package yiguan;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ValidateService {
	  	private static int width = 60;
	    private static int height = 20;
	    private static int codeCount = 4;
	    private static int x = 0;
	    private static int fontHeight;
	    private static int codeY;
	    static char[] codeSequence = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
	            'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
	            'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
	public static void findValidate(HttpServletRequest request,HttpServletResponse response){
		x = width/(codeCount+1);
	    fontHeight=height-2;
	    codeY =height-4;
        BufferedImage buffImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
        Graphics2D g = buffImg.createGraphics();
        Random random = new Random();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
        Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
        g.setFont(font);
        g.setColor(Color.BLACK);
        g.drawRect(0, 0, width - 1, height - 1);
        g.setColor(Color.BLACK);
        for (int i = 0; i < 2; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(x, y, x + xl, y + yl);
        }
        StringBuffer randomCode = new StringBuffer();
        int red = 0, green = 0, blue = 0;
        for (int i = 0; i < codeCount; i++) {
            String strRand = String.valueOf(codeSequence[random.nextInt(36)]);
            red = random.nextInt(255);
            green = random.nextInt(255);
            blue = random.nextInt(255);
            g.setColor(new Color(red, green, blue));
            g.drawString(strRand, (i + 1) * x, codeY);
            randomCode.append(strRand);
        }
        HttpSession session = request.getSession();
        session.setAttribute("validateCode", randomCode.toString());
        session.setAttribute("code", "false");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires",-1);
        response.setContentType("image/jpeg");
        ServletOutputStream sos;
		try {
			sos = response.getOutputStream();
	        ImageIO.write(buffImg, "jpeg", sos);
	        sos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
